package com.yycwxt.modules.admin.cwfy;

import com.yycwxt.common.ReturnResult;
import com.yycwxt.domain.Cwfy;
import com.yycwxt.modules.admin.data_import.AccountData;
import com.yycwxt.modules.admin.data_import.ImpFile;
import com.yycwxt.modules.admin.data_import.ImpFileService;
import com.yycwxt.modules.admin.store.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Api
@RestController
@Validated
@RequestMapping("/Cwfys")
public class CwfyController {

    @Value("${file.location}")
    String filelocation;
    @Value("${file.path}")
    String filepath;
    private final CwfyService cwfyService;
    private final ImpFileService impFileService;

    public CwfyController(CwfyService cwfyService,ImpFileService impFileService){
        this.cwfyService = cwfyService;
        this.impFileService = impFileService;
    }

    @GetMapping()
    @ApiOperation("查询全部")
    public List<Cwfy> selectAll(){return cwfyService.list();}

    @GetMapping("/{id}")
    @ApiOperation("查询财务费用")
    public Cwfy getById(@PathVariable Integer id){
        return cwfyService.getById(id);
    }

    @PostMapping()
    @ApiOperation("添加财务费用")
    public boolean addCwfy(@ApiParam(name = "Cwfy对象",required = true, type = "cwfy") @RequestBody Cwfy cwfy){
        return cwfyService.save(cwfy);
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除财务费用")
    public boolean deleteCwfy(@ApiParam(name = "ID值",required = true, type = "int") @PathVariable Integer id){
        return cwfyService.removeById(id);
    }

    @PutMapping()
    @ApiOperation("修改财务费用")
    public boolean updateCwfy(@ApiParam(name = "Cwfy对象",required = true, type = "cwfy") @RequestBody Cwfy cwfy){
        return cwfyService.updateById(cwfy);
    }

    @PostMapping("/upload")
    @ApiOperation("Excel导入数据")
    public Result excelToDatabase(@ApiParam(value = "是否删除全部历史记录", type = "boolean") @RequestParam boolean deleteHistory,
                                  @ApiParam(value = "上传文件", type = "_file") @RequestPart("file") MultipartFile file) {
        Result result = new Result();
        if(cwfyService.importFileToDB(deleteHistory, file)){
            result.setCode("200");
            result.setMsg("添加成功");
        }else {
            result.setCode("500");
            result.setMsg("添加失败");
        }
        return result;
    }

    // 查询下载文件地址
    @GetMapping("/getCwfyUrl")
    @ApiOperation("获取财务费用文件的URL")
    public ReturnResult getUrl(){
        return ReturnResult.buildSuccessResult(cwfyService.getCwfyUrl());
    }

    @GetMapping("/data")
    @ApiOperation("获取数据")
    public ReturnResult getdata(int zq){
        return ReturnResult.buildSuccessResult(cwfyService.getcwfy(zq));
    }



    @PostMapping("/impCwfy")
    @ApiOperation("财务费用上传")
    public ReturnResult FileUpLoad(@ApiParam(value = "财务费用excel文件", type = "_file") @RequestPart("file") MultipartFile file) {
        ImpFile impFile = new ImpFile();
        if (file.isEmpty()) {
            return ReturnResult.buildFailureResult("文件为空");
        } else {
            try {
                // 保存文件
                // 服务器文件名
                String serverFilename = UUID.randomUUID().toString().substring(0, 8) + ".xlsx";
                // 创建目录
                String path = filelocation + AccountData.getAccountDate();
                System.out.println(path);
                Files.createDirectories(Paths.get(path));
                // 保存
                file.transferTo(Path.of(path, serverFilename));

                // 记录上传文件明细
                impFile.setFilename(file.getOriginalFilename());
                impFile.setName("财务费用");
                impFile.setUrl("download/" + AccountData.getAccountDate() + "/" + serverFilename);
                impFile.setZq(AccountData.getAccountDate());
                impFile.setCreated(LocalDateTime.now());
                impFile.setRemark("财务费用");
                System.out.println(impFile);
                impFileService.save(impFile);

                // 解析excel，记录流水
                cwfyService.impCwfy(file);
                return ReturnResult.buildSuccessResult("导入成功", true);
            } catch (Exception e) {
                impFileService.removeById(impFile);
                return ReturnResult.buildFailureResult(e.toString());
            }
        }
    }

}
